/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

#include "TestResult.h"
#include "Utils/Utils.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

TestResult::TestResult(size_t summaryBufferLenght, size_t logBufferLenght):
errorCount(0), runCount(0), summaryBufferLenght(summaryBufferLenght), logBufferLenght(logBufferLenght),
summary(NULL), log(NULL),
summaryFormat(PROG_MEM_STRING("%s run, %s failed")), logFormat(PROG_MEM_STRING("Test \'%s\' failed!\n\r"))
{



	if(logBufferLenght > 0)
	{
		log = new char[logBufferLenght];
		log[0] = '\0';
	}
}



TestResult::~TestResult()
{
	if(!isNull(summary))
		delete summary;

	if(!isNull(log))
		delete log;
}
void TestResult::testStarted()
{
	runCount++;
}

void TestResult::testFailed(const char * testName)
{
	errorCount++;

	if(logBufferLenght == 0)
		return;

	size_t logLenght = strlen(log);

	if(!isNull(testName) && (logBufferLenght > (logLenght + strlen(logFormat) + strlen(testName) + 1)) )
	{
		sprintf(&log[logLenght], logFormat, testName);
		printf(log);
	}


}

size_t TestResult::getRunCount()
{
	return runCount;
}

size_t TestResult::getErrorCount()
{
	return errorCount;
}

const char * TestResult::getSummary()
{
	char * runString = new(Allocators::STACK) char[15];
	char * errString = new(Allocators::STACK) char[15];

	ultoa(getRunCount(), runString, 10);
	ultoa(getErrorCount(), errString, 10);

	size_t runStringLen = strlen(runString);
	size_t errStringLen = strlen(errString);


	size_t summaryLen = strlen(summaryFormat) + runStringLen + errStringLen + 1; // NEVER FORGET THAT NULL CHAR AGAIN

	if(summaryBufferLenght > summaryLen)
	{
		if(isNull(summary))
			summary = new char[summaryLen];
		else
			summary = new(summary) char[summaryLen];

		sprintf(summary, summaryFormat, runString, errString);
		return summary;
	}

	return "No Summary";
}

const char * TestResult::getLog()
{
	return log;
}
